package com.gxc.aspect;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author GongXincheng
 * @since 2019-10-12 21:06
 */
//@Aspect
//@Component
public class TimeAspect {

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
    public void controllerPointCut() {
    }

    @Around("controllerPointCut()")
    public Object controllerAround(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        String[] parameterNames = signature.getParameterNames();
        Object[] args = joinPoint.getArgs();
        Map<String, Object> bodyJson = new HashMap<>(16);
        for (int i = 0; i < parameterNames.length; i++) {
            Object arg = args[i];
            if (arg instanceof ServletRequest ||
                    arg instanceof ServletResponse ||
                    arg instanceof MultipartFile ||
                    arg instanceof BindingResult ||
                    arg instanceof HttpSession) {
                continue;
            }
            bodyJson.put(parameterNames[i], arg);
        }

        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println("Aspect -> 请求入参JSON：" + objectMapper.writeValueAsString(bodyJson));
        Object proceed = joinPoint.proceed();
        System.out.println("Aspect -> Aspect 执行完成");
        return proceed;
    }

}
